<?php
/**
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/12/08
 */

namespace app\__MODULE__\model;
use think\Model;

class GoodsAttr extends BaseModel
{

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'goods_attr';



    protected function setAttrValuesAttr($value)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    protected function getAttrValuesAttr($value)
    {
        return explode(',', $value);
    }

    /**
     * [createProductAttr description]
     * @param  [array] $attrList  [商品规格 多属性商品有 单属性商品为默认]
     * //多规格
     * [{"value":"大小","detail":["大号","小号"]},{"value":"颜色","detail":["黑色","白色"]}]
     * //单规格
     * [{"value":"规格","detailValue":"","attrHidden":"","detail":["默认"]}]
     * @param  [array] $valueList [商品列表]
     *  //多规格
     *[{"value1":"大号","value2":"黑色","detail":{"大小":"大号","颜色":"黑色"},"pic":"xxx","price":"110""} 
     *  ,{"value1":"大号","value2":"白色","detail":{"大小":"大号","颜色":"白色"},"pic":"xxx","price":"110"}
     *  ]
     *  //单规则
     *  [{"pic":"xxx","price":"110","value1":"规格","detail":{"规格":"默认"}}]
     * @param  [int] $productId [商品id]
     * @return [bool]            
     */
    public static function createProductAttr($attrList, $valueList, $productId)
    { 
        $result = ['attr' => $attrList, 'value' => $valueList];
        $attrValueList = [];    //数组格式，属性值
        $attrNameList = []; //数组格式，属性名称
        foreach ($attrList as $index => $attr) {
            if (!isset($attr['value'])) exception('请输入规则名称!');
            $attr['value'] = trim($attr['value']);
            if (!isset($attr['value'])) exception('请输入规则名称!!');
            if (!isset($attr['detail']) || !count($attr['detail'])) exception('请输入属性名称!');
            unset($attr['detailValue']);  unset($attr['attrHidden']); //删除多余字段
            foreach ($attr['detail'] as $k => $attrValue) {
                $attrValue = trim($attrValue);
                if (empty($attrValue)) exception('请输入正确的属性');
                $attr['detail'][$k] = $attrValue;
                $attrValueList[] = $attrValue;  //单独变量接收属性值
            }
            $attrNameList[] = $attr['value'];  //单独变量接收属性名称
            $attrList[$index] = $attr;
        }
       
        $attrCount = count($attrList);
        foreach ($valueList as $index => $value) {
            if (!isset($value['detail']) || count($value['detail']) != $attrCount) exception('请填写正确的商品信息');
            if (!isset($value['price']) || !is_numeric($value['price']) || floatval($value['price']) != $value['price'])
                exception('请填写正确的商品价格');
            if (!isset($value['stock']) || !is_numeric($value['stock']) || intval($value['stock']) != $value['stock'])
                exception('请填写正确的商品库存');
            if (!isset($value['cost']) || !is_numeric($value['cost']) || floatval($value['cost']) != $value['cost'])
                exception('请填写正确的商品成本价格');
            if (!isset($value['pic']) || empty($value['pic']))
                exception('请上传商品图片');
            foreach ($value['detail'] as $attrName => $attrValue) {
                $attrName = trim($attrName);
                $attrValue = trim($attrValue);
                if (!in_array($attrName, $attrNameList, true)) exception($attrName . '规则不存在');
                if (!in_array($attrValue, $attrValueList, true)) exception($attrName . '属性不存在');
                if (empty($attrName)) exception('请输入正确的属性');
                $value['detail'][$attrName] = $attrValue;
            }
            $valueList[$index] = $value;
        }
        $attrGroup = [];
        $valueGroup = [];
        foreach ($attrList as $k => $value) {
            $attrGroup[] = [
                'product_id' => $productId,
                'attr_name' => $value['value'],
                'attr_values' => $value['detail']
            ];
        }
        foreach ($valueList as $k => $value) {
            sort($value['detail'], SORT_STRING);
            $suk = implode(',', $value['detail']);
            $valueGroup[$suk] = [
                'product_id' => $productId,
                'suk' => $suk,
                'price' => $value['price'],
                'cost' => $value['cost'],
                'ot_price' => $value['ot_price'],
                'stock' => $value['stock'],
                'unique' => GoodsAttrValue::where(['product_id'=>$productId,'suk'=>$suk])->value('unique') ? : '',
                'image' => $value['pic'],
                'bar_code' => $value['bar_code'] ?? ''
            ];
        }
        if (!count($attrGroup) || !count($valueGroup)) exception('请设置至少一个属性!');
        $attrModel = new self;
        $attrValueModel = new GoodsAttrValue;
        if (!self::clearProductAttr($productId)) return false; //先清除商品规则
        $res = false !== $attrModel->saveAll($attrGroup)  //插入属性表
            && false !== $attrValueModel->saveAll($valueGroup) //插入商品属性值表
            && false !== GoodsAttrResult::setResult($result, $productId); //插入商品属性详情表
        if ($res)
            return true;
        else
            exception('编辑商品属性失败!');
    }

    public static function clearProductAttr($productId)
    {
        if (empty($productId) && $productId != 0) exception('商品不存在!');
        $res = false !== self::where('product_id', $productId)->delete()
            && false !== GoodsAttrValue::clearProductAttrValue($productId);
        if (!$res)
            exception('编辑属性失败,清除旧属性失败!');
        else
            return true;
    }

    /**
     * 获取产品属性
     * @param $productId
     * @return array|bool|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getProductAttr($productId)
    {
        if (empty($productId) && $productId != 0) exception('商品不存在!');
        $count = self::where('product_id', $productId)->count();
        if (!$count) exception('商品不存在!');
        return self::where('product_id', $productId)->select()->toArray();
    }



    /**
     * 获取商品属性数据详情
     * @param $productId
     * @return array
     */
    public static function getProductAttrDetail($productId)
    {
        $attrDetail = self::where('product_id', $productId)->order('attr_values asc')->select()->toArray() ?: [];
        $_values = GoodsAttrValue::where('product_id', $productId)->field('product_id,stock,suk,image,unique,price,ot_price')->select();
        $values = [];
        foreach ($_values as $value) {
            $values[$value['suk']] = $value;
        }

        foreach ($attrDetail as $k => $v) {
            $attr = $v['attr_values'];
            foreach ($attr as $kk => $vv) {
                $attrDetail[$k]['attr_value'][$kk]['attr'] = $vv;
                $attrDetail[$k]['attr_value'][$kk]['check'] = false;
            }
        }
        return [$attrDetail, $values];
    }

    public static function uniqueByStock($unique)
    {
        return GoodsAttrValue::where('unique', $unique)->value('stock') ?: 0;
    }

    public static function uniqueByAttrInfo($unique, $field = '*')
    {
        return GoodsAttrValue::field($field)->where('unique', $unique)->find();
    }

    /**
     * 检查商品属性是否存在
     * @param  [int] $productId [商品id]
     * @param  [string] $unique    [属性值]
     * @return [type]            [description]
     */
    public static function issetProductUnique($productId, $unique)
    {
        $res = self::where('product_id', $productId)->find();
        return $res && GoodsAttrValue::where('product_id', $productId)->where('unique', $unique)->count() > 0;
    }
}